package service;

import dao.PlaylistDao;
import dao.CurrentPlaylistDao;
import dao.SongDao;
import dao.UserDao;
import entity.Playlist;
import entity.Song;
import entity.User;
import io.javalin.http.UploadedFile;
import util.EntityConverter;
import util.FileStorageUtil;
import util.ResponseUtil;
import util.ValidationUtil;

import java.nio.file.Files;
import java.nio.file.Paths;
import java.sql.SQLException;
import java.util.*;
import java.util.stream.Collectors;
import java.io.IOException;

public class PlaylistService {
    private static final String DEFAULT_PLAYLIST_COVER = "storage/covers/playlists/default.jpg";
    
    private final PlaylistDao playlistDao;
    private final CurrentPlaylistDao currentPlaylistDao;
    private final SongDao songDao;
    private final UserDao userDao;
    
    public PlaylistService() {
        this.playlistDao = new PlaylistDao();
        this.currentPlaylistDao = new CurrentPlaylistDao();
        this.songDao = new SongDao();
        this.userDao = new UserDao();
    }
    
    // 获取歌单基本信息
    public Map<String, Object> getPlaylistInfo(String playlistId, Long currentUserId) {
        try {
            Playlist playlist = playlistDao.findById(Long.parseLong(playlistId));
            if (playlist == null) {
                return ResponseUtil.error("歌单不存在");
            }
            
            User creator = userDao.findById(playlist.getCreatorId());
            boolean isFavorited = currentUserId != null && 
                playlistDao.isFavorited(playlist.getPlaylistId(), currentUserId);
            
            return ResponseUtil.success(EntityConverter.playlistToMap(playlist, creator.getUsername(), isFavorited));
            
        } catch (SQLException e) {
            e.printStackTrace();
            return ResponseUtil.error("获取歌单信息失败");
        }
    }
    
    // 获取完整歌单
    public List<Map<String, Object>> getFullPlaylist(String playlistId) {
        try {
            List<Song> songs = playlistDao.findSongsByPlaylistId(Long.parseLong(playlistId));
            return songs.stream()
                .map(EntityConverter::songToMap)
                .collect(Collectors.toList());
            
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException("获取歌单歌曲失败");
        }
    }
    
    // 获取用户创建的所有歌单
    public Map<String, Object> getUserPlaylists(Long userId) {
        try {
            List<Playlist> playlists = playlistDao.findByCreatorId(userId);
            List<Map<String, Object>> playlistList = playlists.stream()
                .map(playlist -> {
                    try {
                        User creator = userDao.findById(playlist.getCreatorId());
                        boolean isFavorited = playlistDao.isFavorited(playlist.getPlaylistId(), userId);
                        return EntityConverter.playlistToMap(playlist, creator.getUsername(), isFavorited);
                    } catch (SQLException e) {
                        e.printStackTrace();
                        return null;
                    }
                })
                .filter(Objects::nonNull)
                .collect(Collectors.toList());
            
            return ResponseUtil.success(playlistList);
            
        } catch (SQLException e) {
            e.printStackTrace();
            return ResponseUtil.error("获取用户歌单失败");
        }
    }
    
    // 获取用户收藏的所有歌单
    public Map<String, Object> getFavoritePlaylists(Long userId) {
        try {
            List<Playlist> playlists = playlistDao.findFavoritesByUserId(userId);
            List<Map<String, Object>> playlistList = playlists.stream()
                .map(playlist -> {
                    try {
                        User creator = userDao.findById(playlist.getCreatorId());
                        return EntityConverter.playlistToMap(playlist, creator.getUsername(), true);
                    } catch (SQLException e) {
                        e.printStackTrace();
                        return null;
                    }
                })
                .filter(Objects::nonNull)
                .collect(Collectors.toList());
            
            return ResponseUtil.success(playlistList);
            
        } catch (SQLException e) {
            e.printStackTrace();
            return ResponseUtil.error("获取收藏歌单失败");
        }
    }
    
    // 创建歌单
    public Map<String, Object> createPlaylist(Long userId, String name, String description, 
            UploadedFile coverFile) {
        try {
            // 验证参数
            ValidationUtil.validatePlaylistName(name);
            ValidationUtil.validatePlaylistDescription(description);
            
            // 处理封面文件
            String coverPath = DEFAULT_PLAYLIST_COVER;
            if (coverFile != null) {
                ValidationUtil.validateImageFile(coverFile);
                coverPath = FileStorageUtil.saveCoverFile(coverFile, userId);
            }
            
            // 创建歌单
            Playlist playlist = new Playlist();
            playlist.setName(name);
            playlist.setDescription(description == null ? "" : description);
            playlist.setCoverFilePath(coverPath);
            playlist.setCreatorId(userId);
            
            playlist = playlistDao.create(playlist);
            User creator = userDao.findById(userId);
            
            return ResponseUtil.success("创建成功", 
                EntityConverter.playlistToMap(playlist, creator.getUsername(), false));
            
        } catch (IllegalArgumentException e) {
            return ResponseUtil.error(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseUtil.error("创建歌单失败");
        }
    }
    
    // 删除歌单
    public Map<String, Object> deletePlaylist(Long userId, String playlistId) {
        try {
            Playlist playlist = playlistDao.findById(Long.parseLong(playlistId));
            if (playlist == null) {
                return ResponseUtil.error("歌单不存在");
            }
            
            if (!playlist.getCreatorId().equals(userId)) {
                return ResponseUtil.forbidden();
            }
            
            // 删除封面文件(如果不是默认封面)
            if (!playlist.getCoverFilePath().equals(DEFAULT_PLAYLIST_COVER)) {
                try {
                    FileStorageUtil.deleteFile(playlist.getCoverFilePath());
                } catch (IOException e) {
                    e.printStackTrace();
                    // 即使删除文件失败，也继续删除数据库记录
                }
            }
            
            playlistDao.delete(playlist.getPlaylistId());
            return ResponseUtil.success("删除成功");
            
        } catch (SQLException e) {
            e.printStackTrace();
            return ResponseUtil.error("删除歌单失败");
        }
    }
    
    // 收藏/取消收藏歌单
    public Map<String, Object> toggleFavorite(Long userId, String playlistId, boolean favorite) {
        try {
            playlistDao.toggleFavorite(Long.parseLong(playlistId), userId, favorite);
            return ResponseUtil.success(favorite ? "收藏成功" : "取消收藏成功");
        } catch (SQLException e) {
            e.printStackTrace();
            return ResponseUtil.error(favorite ? "收藏失败" : "取消收藏失败");
        }
    }
    
    // 获取热门歌单
    public Map<String, Object> getHotPlaylists(int limit, Long currentUserId) {
        try {
            List<Playlist> hotPlaylists = playlistDao.findHotPlaylists(limit);
            List<Map<String, Object>> playlistList = new ArrayList<>();
            
            for (Playlist playlist : hotPlaylists) {
                User creator = userDao.findById(playlist.getCreatorId());
                boolean isFavorited = currentUserId != null && 
                    playlistDao.isFavorited(playlist.getPlaylistId(), currentUserId);
                
                playlistList.add(EntityConverter.playlistToMap(playlist, creator.getUsername(), isFavorited));
            }
            
            return ResponseUtil.success(playlistList);
            
        } catch (SQLException e) {
            e.printStackTrace();
            return ResponseUtil.error("获取热门歌单失败");
        }
    }
    
    // 修改歌单信息
    public Map<String, Object> updatePlaylistInfo(Long userId, String playlistId, 
            String name, String description, UploadedFile coverFile) {
        try {
            Playlist playlist = playlistDao.findById(Long.parseLong(playlistId));
            if (playlist == null) {
                return ResponseUtil.error("歌单不存在");
            }
            
            if (!playlist.getCreatorId().equals(userId)) {
                return ResponseUtil.forbidden();
            }
            
            if (name != null) {
                ValidationUtil.validatePlaylistName(name);
                playlist.setName(name);
            }
            
            if (description != null) {
                ValidationUtil.validatePlaylistDescription(description);
                playlist.setDescription(description);
            }
            
            if (coverFile != null) {
                ValidationUtil.validateImageFile(coverFile);
                String newCoverPath = FileStorageUtil.saveCoverFile(coverFile, userId);
                
                // 删除旧封面
                if (!playlist.getCoverFilePath().equals(DEFAULT_PLAYLIST_COVER)) {
                    FileStorageUtil.deleteFile(playlist.getCoverFilePath());
                }
                
                playlist.setCoverFilePath(newCoverPath);
            }
            
            playlistDao.update(playlist);
            User creator = userDao.findById(userId);
            boolean isFavorited = playlistDao.isFavorited(playlist.getPlaylistId(), userId);
            
            return ResponseUtil.success("更新成功", 
                EntityConverter.playlistToMap(playlist, creator.getUsername(), isFavorited));
            
        } catch (IllegalArgumentException e) {
            return ResponseUtil.error(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseUtil.error("更新歌单失败");
        }
    }
    
    // 歌单歌曲管理
    public Map<String, Object> addSongsToPlaylists(Long userId, List<String> songIds, 
            List<String> playlistIds) {
        try {
            // 验证所有歌单的所有权
            for (String playlistId : playlistIds) {
                Playlist playlist = playlistDao.findById(Long.parseLong(playlistId));
                if (playlist == null || !playlist.getCreatorId().equals(userId)) {
                    return ResponseUtil.forbidden();
                }
            }
            
            List<Long> songIdList = songIds.stream()
                .map(Long::parseLong)
                .collect(Collectors.toList());
                
            for (String playlistId : playlistIds) {
                playlistDao.addSongs(Long.parseLong(playlistId), songIdList);
            }
            
            return ResponseUtil.success("添加成功");
            
        } catch (SQLException e) {
            e.printStackTrace();
            return ResponseUtil.error("添加歌曲失败");
        }
    }
    
    public Map<String, Object> removeSongsFromPlaylist(Long userId, String playlistId, 
            List<String> songIds) {
        try {
            Playlist playlist = playlistDao.findById(Long.parseLong(playlistId));
            if (playlist == null || !playlist.getCreatorId().equals(userId)) {
                return ResponseUtil.forbidden();
            }
            
            List<Long> songIdList = songIds.stream()
                .map(Long::parseLong)
                .collect(Collectors.toList());
                
            playlistDao.removeSongs(playlist.getPlaylistId(), songIdList);
            return ResponseUtil.success("移除成功");
            
        } catch (SQLException e) {
            e.printStackTrace();
            return ResponseUtil.error("移除歌曲失败");
        }
    }
    
    // 将歌单添加到播放队列
    public Map<String, Object> addPlaylistToQueue(Long userId, String playlistId) {
        try {
            List<Song> songs = playlistDao.findSongsByPlaylistId(Long.parseLong(playlistId));
            if (songs.isEmpty()) {
                return ResponseUtil.success("歌单为空");
            }
            
            // 获取当前最大位置
            int currentMaxPosition = currentPlaylistDao.getMaxPosition(userId);
            int addedCount = 0;
            
            // 逐个添加歌曲，跳过重复的
            for (Song song : songs) {
                if (!currentPlaylistDao.existsInPlaylist(userId, song.getSongId())) {
                    currentMaxPosition++;
                    currentPlaylistDao.addSongWithPosition(userId, song.getSongId(), currentMaxPosition);
                    addedCount++;
                }
            }
            
            if (addedCount == 0) {
                return ResponseUtil.success("歌曲已全部在播放列表中");
            }
            
            return ResponseUtil.success(String.format("已添加 %d 首歌曲到播放列表", addedCount));
            
        } catch (SQLException e) {
            e.printStackTrace();
            return ResponseUtil.error("添加到播放列表失败");
        }
    }
    
    // 增加播放次数的方法
    public void incrementPlayCount(String playlistId) {
        try {
            playlistDao.incrementPlayCount(Long.parseLong(playlistId));
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}